package oms.dao;

import java.util.List;

import oms.entities.Role;
import oms.entities.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class DAOUser implements DAORepo {
	
	private SessionFactory sessionFactory;
	List<User> list;
	
	public DAOUser(){
		
		sessionFactory = null;
		
		try {
			setUp();
		} catch (Exception e) {
			System.out.println("not OK");
			e.printStackTrace();
		}
		
	}
	
	public List<User> getUsers(Paging page) {
		
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Query q = session.createQuery("from User");
		q.setFirstResult(page.index);
		q.setMaxResults(page.size);
		list = (List<User>) q.list();
		session.getTransaction().commit();
		session.close();
		return list;
		
	}
	
	protected  void setUp() throws Exception {
		sessionFactory = new AnnotationConfiguration().configure()
				.buildSessionFactory();

	}
	
	@Override
	public User create(User user) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		session.close();
		return user;
	}

	@Override
	public User getById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public User getByUserName(String userName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getByFirstName(String firstName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getByLastName(String lastName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getByRole(Role role) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public User update(User user) {
		
		return user;
	}

	@Override
	public User delete(Long id) {
		
		User user = (User) sessionFactory.getCurrentSession().load(
                User.class, id);
		
        if (null != user) {
            sessionFactory.getCurrentSession().delete(user);
        }
		return null;
	}

	@Override
	public User duplicate(Long id) {
		// TODO Auto-generated method stub
		return null;
	}
	
}
